const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const startBtn = document.getElementById('startBtn');
const speedSlider = document.getElementById('speedSlider');
const speedValue = document.getElementById('speedValue');
const scoreElement = document.getElementById('score');

const gridSize = 20;
const tileCount = canvas.width / gridSize;
let speed = 5;
let score = 0;
let gameRunning = false;
let gameLoop;

let snake = [
    {x: 10, y: 10}
];
let food = {
    x: Math.floor(Math.random() * tileCount),
    y: Math.floor(Math.random() * tileCount)
};
let velocity = {x: 0, y: 0};

function drawSnake() {
    ctx.fillStyle = '#4CAF50';
    snake.forEach(segment => {
        ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize);
    });
}

function drawFood() {
    ctx.fillStyle = '#FF5722';
    ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize);
}

function moveSnake() {
    const head = {x: snake[0].x + velocity.x, y: snake[0].y + velocity.y};
    snake.unshift(head);
    
    if (head.x === food.x && head.y === food.y) {
        score += 10;
        scoreElement.textContent = score;
        food = {
            x: Math.floor(Math.random() * tileCount),
            y: Math.floor(Math.random() * tileCount)
        };
    } else {
        snake.pop();
    }
}

function checkCollision() {
    const head = snake[0];
    
    // 撞墙检测
    if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount) {
        gameOver();
        return;
    }
    
    // 撞自己检测
    for (let i = 1; i < snake.length; i++) {
        if (head.x === snake[i].x && head.y === snake[i].y) {
            gameOver();
            return;
        }
    }
}

function gameOver() {
    clearInterval(gameLoop);
    gameRunning = false;
    startBtn.textContent = '重新开始';
    alert(`游戏结束！你的得分是: ${score}`);
}

function updateGame() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    moveSnake();
    checkCollision();
    drawSnake();
    drawFood();
}

function startGame() {
    if (gameRunning) return;
    
    // 重置游戏状态
    snake = [{x: 10, y: 10}];
    velocity = {x: 0, y: 0};
    score = 0;
    scoreElement.textContent = score;
    food = {
        x: Math.floor(Math.random() * tileCount),
        y: Math.floor(Math.random() * tileCount)
    };
    
    gameRunning = true;
    startBtn.textContent = '游戏中...';
    
    // 设置游戏循环
    gameLoop = setInterval(updateGame, 1000 / speed);
}

// 事件监听
startBtn.addEventListener('click', startGame);

speedSlider.addEventListener('input', () => {
    speed = parseInt(speedSlider.value);
    speedValue.textContent = speed;
    
    if (gameRunning) {
        clearInterval(gameLoop);
        gameLoop = setInterval(updateGame, 1000 / speed);
    }
});

// 键盘控制
document.addEventListener('keydown', (e) => {
    if (!gameRunning) return;
    
    switch (e.key) {
        case 'ArrowUp':
            if (velocity.y === 0) velocity = {x: 0, y: -1};
            break;
        case 'ArrowDown':
            if (velocity.y === 0) velocity = {x: 0, y: 1};
            break;
        case 'ArrowLeft':
            if (velocity.x === 0) velocity = {x: -1, y: 0};
            break;
        case 'ArrowRight':
            if (velocity.x === 0) velocity = {x: 1, y: 0};
            break;
    }
});